package cn.michael.dev.data.structure.tree.traverse;

import cn.michael.dev.entity.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hufenggang on 2021/9/24.
 *
 * 二叉树的前序遍历
 */
public class BinaryTreeBeforeTraverse {

    /**
     * 前序遍历二叉树
     *
     * @param root
     * @return
     */
    public List<Integer> beforeTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        traverse(root, res);
        return res;
    }

    public void traverse(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        traverse(root.left, res);
        traverse(root.right, res);
    }
}
